//评估记录
import * as React from 'react';
import axios from 'axios';
import {
  TreeSelect,
  Modal,
  Row,
  Col,
  DatePicker,
  notification,
  Menu,
  Steps,
  Dropdown,
  Icon,
  Input,
  Table,
  Button,
  Form,
  InputNumber,
} from 'antd';
import { connect } from 'dva';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { formatTreeData } from '../../components/commonAips';
import Api from '../../services/apis';
import styles from "./style.less";

const confirm = Modal.confirm;
//时间组件
const { RangePicker } = DatePicker;
const Step = Steps.Step;
const FormItem = Form.Item;
import moment from 'moment';
import 'moment/locale/zh-cn';
//获取默认时间并在下面转换为moment格式
const nowYear = new Date().getFullYear();
const startTime = `${nowYear}-01-01`;
const [endTimeMonth, endTimeDay] = [
  new Date().getMonth() + 1 < 10 ? `0${new Date().getMonth() + 1}` : new Date().getMonth() + 1,
  new Date().getDate() < 10 ? `0${new Date().getDate()}` : new Date().getDate(),
];
const endTime = `${nowYear}-${endTimeMonth}-${endTimeDay}`;


@connect(({ user, project, activities, chart, loading }) => ({
  currentUser: user.currentUser,
  currentUserLoading: loading.effects['user/fetchCurrent']
}))


class UserManagement extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      number: '',
      name: '',
      modalVisible: false,
      modifyVisible: false,
      newNumber: '',
      newName: '',
      newPassword: '',
      samePassword: '',
      newPhone: '',
      newDepartment: '',
      userId: '',
      tableData: [],
      current: 1,
      pageSize: 0,
      orgTreeData: [],
      areaTreeDate: [],
    };
  }

  //获取表格数据
  sendData = () => {
    let that = this;
    axios
      .post(Api.umTableDatas, {
        userCode: that.state.number,
        userName: that.state.name,
        currentPage: that.state.current,
      })
      .then(function (resp) {
        const {data} = resp
        if (data.list.length == 0) {
          notification.destroy();
          notification['warning']({
            message: '暂无数据',
          });
        }

        data.list.forEach((d, i, arr) => {
          d.key = i;
          d.action = d.userState == '1' ? '解冻' : '冻结';
          d.userState = d.userState == '1' ? '已冻结' : '未冻结';
        });
        that.setState({
          tableData: data.list,
          pageSize: data.pageSize,
          current: data.currentPage,
          totalSize: data.totalSize,
        });
      });
  };

  componentWillMount() {
    const that = this;
    //获取表格数据
    this.sendData();

    //获取部门下拉树

    axios.post(Api.umGetOrganizationTree, {}).then(function (resp) {
        const {data} = resp;
      if (data) {
        let treeData = new Array(data);
        formatTreeData(treeData, 'orgName', 'orgLevelFormat', 'orgId', 'childOrgList');
        that.setState({ orgTreeData: treeData });
      }
    });

    //获取地区下拉树

    axios.post(Api.umGetAreaTree, {}).then(function (resp) {
      const {data} = resp;
      if (data) {
        let treeData = new Array(data);
        formatTreeData(treeData, 'name', 'areaLevelFormat', 'areaId', 'childAreaList');
        that.setState({ areaTreeDate: treeData });
      }
    });
  }

  //添加用户
  addUser = () => {
    let that = this;
    if (!that.state.newNumber) {
      notification.destroy();
      notification['warning']({
        message: '请填写工号！',
      });
    } else if (!that.state.newPassword) {
      notification.destroy();
      notification['warning']({
        message: '请填写密码！',
      });
    } else if (that.state.newPassword != that.state.samePassword) {
      notification.destroy();
      notification['warning']({
        message: '确认密码与重复密码不一致！',
      });
    } else if (!that.state.newName) {
      notification.destroy();
      notification['warning']({
        message: '请填写姓名！',
      });
    } else if (!that.state.newPhone) {
      notification.destroy();
      notification['warning']({
        message: '请填写联系电话！',
      });
    } else if (!that.state.newDepartment) {
      notification.destroy();
      notification['warning']({
        message: '请填写单位！',
      });
    } else {
      //添加
      axios
        .post(Api.umAddUser, {
          userCode: that.state.newNumber,
          userPassword: that.state.newPassword,
          userName: that.state.newName,
          phoneNumber: that.state.newPhone,
          orgId: that.state.newDepartment,
        })
        .then(function (resp) {
          const {data} = resp;
          if (data.code == 1) {
            notification.destroy();
            notification['success']({
              message: data.msg,
            });
            //关闭弹框
            that.setModalVisible(false);
            //刷新列表
            that.sendData();
          } else if (data.code == 2) {
            notification.destroy();
            notification['warning']({
              message: data.msg,
            });
          } else if (data.code == 0) {
            notification.destroy();
            notification['error']({
              message: data.msg,
            });
          }
        });
    }
  };

  pageChange = (page, pageSize) => {
    this.setState({ current: page }, () => {
      this.sendData();
    });
  };

  query = () => {
    this.setState({ current: 1 }, () => {
      this.sendData();
    });
  };

  resetForm() {
    this.setState({
      number: '',
      name: '',
    });
  }

  changeNumber = e => {
    this.setState({ number: e.target.value });
  };

  changeName = e => {
    this.setState({ name: e.target.value });
  };

  changeUser = (userCode, userId) => {
    let that = this;
    axios
      .post(Api.umGetUserByCode, {
        userCode: userCode,
      })
      .then(function (resp) {
        const {data} = resp;
        if (data) {
          that.setState({
            newNumber: data.userCode,
            newName: data.userName,
            newPhone: data.phoneNumber,
            newDepartment: data.orgId + '',
            userId: userId,
          });
          that.setmodifyVisible(true);
        }
      });
  };

  updateUser = () => {
    let that = this;
    let param = new URLSearchParams();

    if (!that.state.newNumber) {
      notification.destroy();
      notification['warning']({
        message: '请填写工号！',
      });
    } else if (!that.state.newName) {
      notification.destroy();
      notification['warning']({
        message: '请填写姓名！',
      });
    } else if (!that.state.newPhone) {
      notification.destroy();
      notification['warning']({
        message: '请填写联系电话！',
      });
    } else if (!that.state.newDepartment) {
      notification.destroy();
      notification['warning']({
        message: '请填写单位！',
      });
    } else {
      //添加
      const that = this;

      axios
        .post(Api.umUpdateUser, {
          userId: that.state.userId,
          userCode: that.state.newNumber,
          userName: that.state.newName,
          phoneNumber: that.state.newPhone,
          orgId: that.state.newDepartment,
        })
        .then(function (resp) {
          const {data} = resp;
          if (data.code == 1) {
            notification.destroy();
            notification['success']({
              message: data.msg,
            });
            //关闭弹框
            that.setmodifyVisible(false);
            //刷新列表
            that.sendData();
          } else if (data.code == 2) {
            notification.destroy();
            notification['warning']({
              message: data.msg,
            });
          } else if (data.code == 0) {
            notification.destroy();
            notification['error']({
              message: data.msg,
            });
          }
        });
    }
  };

  setModalVisible(modalVisible) {
    this.setState({
      modalVisible: modalVisible,
      newNumber: '',
      newName: '',
      newPassword: '',
      samePassword: '',
      newPhone: '',
      newDepartment: '',
    });
  }

  setmodifyVisible = modifyVisible => {
    this.setState({
      modifyVisible: modifyVisible,
    });
  };

  frozenUser = (userCode, state) => {
    let that = this;

    confirm({
      title: state == '已冻结' ? '解冻确认' : '冻结确认',
      content: state == '已冻结' ? '确认要解冻该用户？' : '确认要冻结该用户？',
      onOk() {
        axios
          .post(Api.umUpdateUserState, {
            userCode: userCode,
          })
          .then(function (resp) {
            const {data} = resp;
            console.log(data);
            if (data.code == 1) {
              notification.destroy();
              notification['success']({
                message: data.msg,
              });

              //刷新列表
              that.sendData();
            } else if (data.code == 0) {
              notification.destroy();
              notification['error']({
                message: data.msg,
              });
            }
          });
      },
      onCancel() { },
    });
  };
  addNumber = e => {
    this.setState({ newNumber: e.target.value });
  };

  addName = e => {
    this.setState({ newName: e.target.value });
  };

  addPassword = e => {
    this.setState({ newPassword: e.target.value });
  };

  addSamePassword = e => {
    this.setState({ samePassword: e.target.value });
  };

  addPhone = e => {
    this.setState({ newPhone: e.target.value });
  };

  addDepartment = value => {
    this.setState({ newDepartment: value });
  };


  render() {
    const {
      currentUserLoading,
    } = this.props;

    let that = this;
    //表格表头
    const columns = [
      {
        title: '工号',
        dataIndex: 'userCode',
        key: 'userCode',
      },
      {
        title: '姓名',
        dataIndex: 'userName',
        key: 'userName',
      },
      {
        title: '所属区域',
        dataIndex: 'areaName',
        key: 'areaName',
      },
      {
        title: '状态',
        dataIndex: 'userState',
        key: 'userState',
      },
      {
        title: '联系电话',
        dataIndex: 'phoneNumber',
        key: 'phoneNumber',
      },
      {
        title: '操作',
        dataIndex: 'action',
        key: 'action',
        render: (text, item, index) => (
          <div key={index}>
              <a href="javascript:;"
              onClick={() => {
                that.changeUser(item.userCode, item.userId);
              }}
            >
                修改
              </a>
              &emsp;
              <a href="javascript:;"
              onClick={() => {
                that.frozenUser(item.userCode, item.userState);
              }}
            >
              {text}
              </a>
          </div>
        ),
      },
    ];

    const treeData = [
      {
        title: 'Node1',
        value: '1',
        key: '1',
        children: [
          {
            title: 'Child Node1',
            value: '1-1',
            key: '1-1',
          },
          {
            title: 'Child Node2',
            value: '1-2',
            key: '1-2',
          },
        ],
      },
      {
        title: 'Node2',
        value: '2',
        key: '2',
      },
    ];

    return (
      <PageHeaderWrapper
        loading={currentUserLoading}
      >
        <div className="mainContainer">
          <div className='contentHeader'>
            <div className="contentHeaderTitle">
              <p>用户管理</p>
              <p>USER MANAGEMENT</p>
            </div>
          </div>
          <div className='mrb15'>
            <Form layout="inline" align='center'>
              <FormItem>
                  <span className="label">工号：</span>
                  <Input
                    value={this.state.number}
                    data-inp="zdbh"
                    onChange={this.changeNumber.bind(this)}
                    placeholder="请输入工号"
                  />
                </FormItem>

                <FormItem>
                  <span className="label">姓名：</span>
                  <Input
                    value={this.state.name}
                    onChange={this.changeName.bind(this)}
                    data-inp="zldz"
                    placeholder="请输入姓名"
                  />
                </FormItem>
                <Row gutter={24} style={{ textAlign: 'center'}}>
                  <Button icon='search' type="primary" className="evfilterbtn" onClick={this.query.bind(this)}>
                    查询
                  </Button>
                  &emsp;
                  <Button
                    onClick={this.resetForm.bind(this)}
                    type="primary"
                    htmlType="reset"
                    className="evfilterbtn" icon="reload"
                  >
                    重置
                </Button>
                  &emsp;
                  <Button
                    type="primary" icon="plus-circle"
                    onClick={() => this.setModalVisible(true)}
                  >
                    新增
                  </Button>
                </Row>
            </Form>
          </div>

          <Row className="evtablebox">
            
            <Row className="choicedBox">
              <Table
                bordered={true}
                scroll={{x:true}}
                align='center'
                columns={columns}
                dataSource={this.state.tableData}
                pagination={{
                  defaultPageSize: that.state.pageSize,
                  current: that.state.current,
                  onChange: that.pageChange,
                  total: that.state.totalSize,
                  showTotal: total => `共 ${total} 项`
                }}
              />
            </Row>
          </Row>

          <Modal
            title="基本信息"
            wrapClassName="vertical-center-modal"
            visible={this.state.modalVisible}
            onOk={() => this.addUser()}
            onCancel={() => this.setModalVisible(false)}
            width={830}
          >
            <Row gutter={24} className={styles.modalForm}>
              <Col span={8}>
                <span className={styles.label}>
                  <span style={{ color: 'red' }}>*</span>工号
              </span>
                <Input
                  value={this.state.newNumber}
                  data-inp="zdbh"
                  onChange={this.addNumber.bind(this)}
                  placeholder=""
                />
              </Col>

              <Col span={8}>
                <span className={styles.label}>
                  <span style={{ color: 'red' }}>*</span>姓名
              </span>
                <Input
                  value={this.state.newName}
                  onChange={this.addName.bind(this)}
                  data-inp="zldz"
                  placeholder=""
                />
              </Col>
              <Col span={8}>
                <span className={styles.label}>
                  <span style={{ color: 'red' }}>*</span>密码
              </span>
                <Input
                  value={this.state.newPassword}
                  data-inp="zdbh"
                  onChange={this.addPassword.bind(this)}
                  placeholder=""
                />
              </Col>

              <Col span={8}>
                <span className={styles.label}>
                  <span style={{ color: 'red' }}>*</span>确认密码
              </span>
                <Input
                  value={this.state.samePassword}
                  onChange={this.addSamePassword.bind(this)}
                  data-inp="zldz"
                  placeholder=""
                />
              </Col>
              <Col span={8}>
                <span className={styles.label}>
                  <span style={{ color: 'red' }}>*</span>联系电话
                </span>
                <Input
                  value={this.state.newPhone}
                  data-inp="zdbh"
                  onChange={this.addPhone.bind(this)}
                  placeholder=""
                />
              </Col>
              <Col span={8}>
                <span className={styles.label}>
                  <span style={{ color: 'red' }}>*</span>单位
              </span>
                <TreeSelect
                  value={this.state.newDepartment}
                  dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                  treeData={this.state.orgTreeData}
                  treeDefaultExpandedKeys={['1']}
                  allowClear={true}
                  onChange={this.addDepartment}
                />
              </Col>
            </Row>
          </Modal>

          <Modal
            title="基本信息"
            wrapClassName="vertical-center-modal"
            visible={this.state.modifyVisible}
            onOk={() => this.updateUser()}
            onCancel={() => this.setmodifyVisible(false)}
            width={830}
          >
            <Row gutter={24} className={styles.modalForm}>
              <Col span={8}>
                <span className={styles.label}>
                  <span style={{ color: 'red' }}>*</span>工号
              </span>
                <Input
                  value={this.state.newNumber}
                  data-inp="zdbh"
                  onChange={this.addNumber.bind(this)}
                  placeholder=""
                />
              </Col>

              <Col span={8}>
                <span className={styles.label}>
                  <span style={{ color: 'red' }}>*</span>姓名
              </span>
                <Input
                  value={this.state.newName}
                  onChange={this.addName.bind(this)}
                  data-inp="zldz"
                  placeholder=""
                />
              </Col>
              <Col span={8}>
                <span className={styles.label}>
                  <span style={{ color: 'red' }}>*</span>联系电话
              </span>
                <Input
                  value={this.state.newPhone}
                  data-inp="zdbh"
                  onChange={this.addPhone.bind(this)}
                  placeholder=""
                />
              </Col>
              <Col span={8}>
                <span className={styles.label}>
                  <span style={{ color: 'red' }}>*</span>单位
              </span>
                <TreeSelect
                  value={this.state.newDepartment}
                  dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                  treeData={this.state.orgTreeData}
                  placeholder="Please select"
                  treeDefaultExpandAll={true}
                  allowClear={true}
                  onChange={this.addDepartment}
                />
              </Col>
            </Row>
          </Modal>
        </div>
      </PageHeaderWrapper>
    );
  }
}

export default UserManagement;
